#!/usr/bin/env bash

DOCKERIMGNAME=debian-image-builder

docker build . --tag $DOCKERIMGNAME

docker run -it --rm --privileged -v/dev:/dev -v$(pwd):/src \
    --entrypoint=/bin/bash $DOCKERIMGNAME -c '
cd /src

mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc || true
aarch64_magic="\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00"
aarch64_mask="\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff"
[ ! -f /proc/sys/fs/binfmt_misc/qemu-aarch64-ocf ] && echo ":qemu-aarch64-ocf:M::$aarch64_magic:$aarch64_mask:/usr/bin/qemu-aarch64-static:OCF" > /proc/sys/fs/binfmt_misc/register || true

[ ! -d debian-cloud-images ] && git clone --branch bookworm --single-branch --depth 1 https://salsa.debian.org/cloud-team/debian-cloud-images.git

./debian-cloud-images-patch.sh

cd debian-cloud-images

losetup -D

make image_bookworm_nocloud_arm64

qemu-img convert -O qcow2 image_bookworm_nocloud_arm64.raw image_bookworm_nocloud_arm64.qcow2

cp -r /usr/share/qemu-efi-aarch64/QEMU_EFI.fd .
'
